const http = require('../../utils/http.js');
const { checkLoginAndRedirect, autoLogin, isLoggedIn, setAppResumedFromBackground, setUserOnlineStartTime } = require('../../utils/auth.js');

Page({
  data: {
    period: '',
    rule: '两步通关，抽本周天选',
    tasks: [],
    canLottery: false,
    loading: false,
    showResult: false,
    lotteryResult: null
  },

  onLoad() {
    // 检查登录状态
    if (!checkLoginAndRedirect('抽奖')) {
      return;
    }
    this.loadPageData();
  },

  // 加载页面数据
  async loadPageData() {
    try {
      await Promise.all([
        this.loadPeriod(),
        this.loadLotteryStats(),
        this.checkEligibility()
      ]);
    } catch (error) {
      console.error('加载页面数据失败:', error);
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  // 加载期数
  async loadPeriod() {
    try {
      const res = await http.get('/period/lottery');
      if (res.data.code === 200) {
        this.setData({
          period: res.data.data + '期'
        });
      }
    } catch (error) {
      console.error('获取期数失败:', error);
    }
  },

  // 加载抽奖统计配置
  async loadLotteryStats() {
    try {
      const res = await http.get('/api/system/config/lotteryStats');
      if (res.data.code === 200) {
        const { stepThreshold, consecutiveDays } = res.data.data;
        const tasks = [
          { 
            desc: `完成 ${stepThreshold} 步/周步数任务\n推荐 ${Math.ceil(stepThreshold/7)} 步/天，稳步前进更轻松哦`, 
            btn: '去完成',
            type: 'step',
            threshold: stepThreshold
          },
          { 
            desc: `解锁${consecutiveDays}张历史事件卡片\n每日登录，自动解锁1张历史卡片`, 
            btn: '去完成',
            type: 'streak',
            threshold: consecutiveDays
          }
        ];
        this.setData({ tasks });
      }
    } catch (error) {
      console.error('获取抽奖统计失败:', error);
    }
  },

  // 检查抽奖资格
  async checkEligibility() {
    try {
      const res = await http.get('/api/lottery/checkEligibility?userCode=111');
      if (res.data.code === 200) {
        this.setData({
          canLottery: res.data.data
        });
      }
    } catch (error) {
      console.error('检查抽奖资格失败:', error);
    }
  },

  // 检查任务完成状态
  async checkTaskStatus() {
    try {
      const res = await http.get('/api/user/checkLotteryEligibility?userCode=111');
      if (res.data.code === 200) {
        const { streakCondition, stepCondition } = res.data.data;
        const tasks = this.data.tasks.map((task, index) => {
          let isCompleted = false;
          if (index === 0) {
            isCompleted = stepCondition >= task.threshold;
          } else if (index === 1) {
            isCompleted = streakCondition >= task.threshold;
          }
          return {
            ...task,
            isCompleted,
            btn: isCompleted ? '已完成' : '去完成'
          };
        });
        this.setData({ tasks });
      }
    } catch (error) {
      console.error('检查任务状态失败:', error);
    }
  },

  // 开始抽奖
  async startLottery() {
    if (!this.data.canLottery) {
      wx.showToast({ title: '暂不符合抽奖条件', icon: 'none' });
      return;
    }

    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      const res = await http.post('/api/lottery/perform?userCode=111');
      if (res.data.code === 200) {
        this.setData({
          lotteryResult: res.data.data,
          showResult: true
        });
      } else {
        wx.showToast({ title: res.data.msg || '抽奖失败', icon: 'none' });
      }
    } catch (error) {
      console.error('抽奖失败:', error);
      wx.showToast({ title: '抽奖失败，请重试', icon: 'none' });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 关闭抽奖结果弹窗
  closeResult() {
    this.setData({
      showResult: false,
      lotteryResult: null
    });
  },

  // 任务按钮点击
  onTaskClick(e) {
    const index = e.currentTarget.dataset.index;
    const task = this.data.tasks[index];
    
    if (task.isCompleted) {
      wx.showToast({ title: '任务已完成', icon: 'success' });
    } else {
      wx.showToast({ title: '请完成任务后再来抽奖', icon: 'none' });
    }
  },

  onShow() {
    console.log('抽奖页面显示 - 小程序重新进入前台');
    
    // 检查登录状态，如果已登录则尝试自动登录
    if (isLoggedIn()) {
      console.log('检测到用户已登录，尝试自动登录验证');
      this.performAutoLogin();
    } else {
      console.log('用户未登录，跳转到登录页面');
      wx.redirectTo({ url: '/pages/login/login' });
      return;
    }
  },

  /**
   * 执行自动登录
   */
  performAutoLogin() {
    autoLogin().then((userInfo) => {
      console.log('抽奖页面自动登录成功，用户信息:', userInfo);
      // 自动登录成功，更新页面数据
      this.checkTaskStatus();
      // 重置后台状态
      setAppResumedFromBackground(false);
      // 重置用户在线开始时间
      setUserOnlineStartTime(Date.now());
    }).catch((error) => {
      console.error('抽奖页面自动登录失败:', error);
      // 自动登录失败，跳转到登录页面
      wx.redirectTo({ url: '/pages/login/login' });
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
}); 